package com.studyroom.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.Result;
import com.studyroom.entity.Announcement;
import com.studyroom.service.AnnouncementService;
import com.studyroom.dto.SearchDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/admin/announcements")
public class AnnouncementController {
    private static final Logger log = LoggerFactory.getLogger(AnnouncementController.class);

    @Autowired
    private AnnouncementService announcementService;

    @GetMapping
    public Result<IPage<Announcement>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer status) {
        
        SearchDTO params = new SearchDTO();
        params.setCurrent(current);
        params.setSize(size);
        params.setKeyword(title);
        params.setStatus(status);
        
        return Result.success(announcementService.search(params));
    }

    @PostMapping
    public Result<?> add(@RequestBody Announcement announcement) {
        LocalDateTime now = LocalDateTime.now();
        announcement.setCreatedAt(now);
        announcement.setUpdatedAt(now);

        announcementService.save(announcement);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Long id, @RequestBody Announcement announcement) {
        LocalDateTime now = LocalDateTime.now();
        announcement.setUpdatedAt(now);
        announcement.setId(id);
        announcementService.updateById(announcement);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        announcementService.removeById(id);
        return Result.success();
    }

    @PostMapping("/search")
    public Result<IPage<Announcement>> search(@RequestBody SearchDTO params) {
        return Result.success(announcementService.search(params));
    }

    @GetMapping("/announcements")
    public Result getAnnouncements() {
        try {
            return Result.success(announcementService.getPublishedAnnouncements());
        } catch (Exception e) {
            log.error("获取公告列表失败", e);
            return Result.error("获取公告列表失败");
        }
    }

    @GetMapping("/{id}")
    public Result getAnnouncementById(@PathVariable Long id) {
        try {
            return Result.success(announcementService.getAnnouncementById(id));
        } catch (Exception e) {
            log.error("获取公告详情失败", e);
            return Result.error("获取公告详情失败");
        }
    }
} 